package com.outlook.util.edit;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.outlook.domain.User;

/**
 * parser entity to a POJO in JSON for edit panel
 * type,  name, value, range, attribute
 * @author watson
 */
@SuppressWarnings("unchecked")
public class EntityPaser {
	
	public static JSONArray paser(Class clazz, Object object) {
		Field[] fields = clazz.getDeclaredFields();
		Method[] methods = clazz.getMethods();
		JSONArray array = new JSONArray();
		JSONObject jsonObject = null;
		for(Field field : fields) {
			final Annotation[] declaredAnnotations = field.getDeclaredAnnotations();
			if(AttributeParser.isContainExcude(declaredAnnotations))
				continue;
			jsonObject = new JSONObject();
			jsonObject.put("type", field.getType());
			jsonObject.put("name", field.getName());
//			if(isDeclared(field.getName(), methods)) {
				jsonObject.put("value", getValue(field.getName(), methods, clazz, object));
//			}
			final Map<String, Object> map = AttributeParser.parser(declaredAnnotations);
			if(null != map && !map.isEmpty())
				jsonObject.put("attribute", map);
			array.add(jsonObject);
		}
		return array;
	}

	public static Object getValue(String name, Method[] methods, Class clazz, Object object) {
		for(Method method : methods) {
			if(method.getName().equalsIgnoreCase("get"+name)) {
				try {
					Object[] objects = {};
					return method.invoke(object, objects);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		return null;
	}

	public boolean isDeclared(String name, Method[] methods) {
		for(Method method : methods) {
			if(method.getName().equalsIgnoreCase("get"+name)) {
				return true;
			}
		}
		return false;
	}
	
	public static void main(String[] args) {
		User user = new User();
		user.setAddress("address");
		user.setAge(25);
		user.setArticle("article");
		user.setDescription("description");
		user.setId(1);
		user.setName("name");
		user.setPassword("password");
		user.setPhoto("photo");
		user.setSex(0);
		user.setTelphone("telphone");
		
		JSONArray jsonObject = paser(User.class, user);
		
		System.out.println(jsonObject.toString());
	}

}